import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import io.fabric8.kubernetes.api.model.extensions.DeploymentSpec;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;

import java.util.*;

/**
 * @author yintongjiang
 * @params
 * @since 2017/11/20
 */
public class Main {
    public static void main(String[] args) {
        Config config = new ConfigBuilder().withNamespace("default").withMasterUrl("http://10.112.101.90:8080/").build();
        KubernetesClient client = new DefaultKubernetesClient(config);
        for (Namespace namespace : client.namespaces().list().getItems()) {
            System.out.println(namespace.getApiVersion());
        }
        //        testCreatePv_Rbd(client);
        //        testCreatePvc(client);
        //        testCreatePv_CephFS(client);
        //        testCreatePvcFS(client);
        //        Namespace ns= new NamespaceBuilder().withNewMetadata()
        //                .withName("abcd").endMetadata().build();
        //        ObjectMeta metadata =new ObjectMeta();
        //        Map<String,String> labels = new HashMap<String, String>();
        //        labels.put("label1", "abcd");
        //        metadata.setLabels(labels);
        //        metadata.setNamespace("abcd");
        //        metadata.setName("abcd");
        //        ns.setMetadata(metadata);
        //        client.namespaces().create(ns);
        //        client.namespaces().delete(ns);
        //        client.namespaces().withName("abcd").delete();
        createDeployment(client);
//        deleteDeployment(client);
//        createService(client);


    }

    public static void createPod(KubernetesClient kubernetesClient) {
        Pod pod = new Pod();
        ObjectMeta metadata1 = new ObjectMeta();
        metadata1.setName("autotest");
        metadata1.setNamespace("default");
        pod.setKind("Deployment");
        pod.setApiVersion("extensions/v1beta1");
        pod.setMetadata(metadata1);
        Container container = new Container();
        container.setName("autotest");
        container.setImage("10.112.101.90/cloudzone/autotest:2.0");
        List<Container> containers = new ArrayList<Container>();
        containers.add(container);
        PodSpec podSpec = new PodSpec();
        podSpec.setContainers(containers);
        pod.setSpec(podSpec);
        kubernetesClient.pods().create(pod);
    }

    private static void createDeployment(KubernetesClient kubernetesClient) {
        kubernetesClient.extensions().deployments().create(getDeployment());
    }

    private static Deployment getDeployment() {
        Deployment deployment = new Deployment();
        deployment.setApiVersion("extensions/v1beta1");
        deployment.setKind("Deployment");
        ObjectMeta metadata1 = new ObjectMeta();
        metadata1.setName("autotest");
        metadata1.setNamespace("default");
        metadata1.setLabels(new HashMap<String, String>() {{
            put("app", "autotest");
        }});
        deployment.setMetadata(metadata1);
        final Container container = new Container();
        container.setName("autotest");
        container.setImage("10.112.101.90/cloudzone/autotest:2.0");
        List<ContainerPort> ports = new ArrayList<ContainerPort>() {{
            ContainerPort containerPort = new ContainerPort();
            containerPort.setContainerPort(8080);
            add(containerPort);
        }};
        container.setPorts(ports);
        ResourceRequirements resourceRequirements=new ResourceRequirements();
        resourceRequirements.setRequests(new HashMap<String, Quantity>(){{
            put("cpu",new Quantity("0.5"));
            put("memory",new Quantity("500Mi"));

        }});
        resourceRequirements.setLimits(new HashMap<String, Quantity>(){{
            put("cpu",new Quantity("0.6"));
            put("memory",new Quantity("600Mi"));
        }});
        container.setResources(resourceRequirements);
        List<Container> containers = new ArrayList<Container>();
        containers.add(container);
        DeploymentSpec deploymentSpec = new DeploymentSpec();
        deploymentSpec.setReplicas(3);
        PodTemplateSpec templateSpec = new PodTemplateSpec();
        PodSpec podSpec = new PodSpec();
        podSpec.setContainers(containers);
        ObjectMeta metadata2 = new ObjectMeta();
        metadata2.setName("autotest");
        metadata2.setLabels(new HashMap<String, String>() {{
            put("app", "autotest");
        }});
        templateSpec.setMetadata(metadata2);
        templateSpec.setSpec(podSpec);
        deploymentSpec.setTemplate(templateSpec);
        deployment.setSpec(deploymentSpec);
        return deployment;
    }

    public static void deleteDeployment(KubernetesClient kubernetesClient) {
        kubernetesClient.extensions().deployments().delete(getDeployment());
    }

    public static void createService(KubernetesClient kubernetesClient){
        Service service=new Service();
        service.setApiVersion("v1");
        service.setKind("Service");
        ObjectMeta metadata1 = new ObjectMeta();
        metadata1.setName("autotest");
        metadata1.setNamespace("default");
        metadata1.setLabels(new HashMap<String, String>() {{
            put("app", "autotest");
        }});
        service.setMetadata(metadata1);
        ServiceSpec serviceSpec=new ServiceSpec();
        List<ServicePort> ports = new ArrayList<ServicePort>() {{
            ServicePort servicePort = new ServicePort();
            servicePort.setName("auto-test");
            servicePort.setNodePort(8809);
            servicePort.setTargetPort(new IntOrString(8080));
            servicePort.setPort(8080);
            add(servicePort);
        }};
        serviceSpec.setPorts(ports);
        serviceSpec.setType("NodePort");
        serviceSpec.setSelector(new HashMap<String, String>() {{
            put("app", "autotest");
        }});
        service.setSpec(serviceSpec);
        kubernetesClient.services().create(service);
    }

    /**
     * 创建pv信息，挂载CephFS存储
     *
     * @param kubernetesClient
     */
    public static void testCreatePv_CephFS(KubernetesClient kubernetesClient) {
        PersistentVolume pv = new PersistentVolume();
        pv.setApiVersion("v1");
        pv.setKind("PersistentVolume");

        ObjectMeta meta = new ObjectMeta();
        meta.setAnnotations(new HashMap<String, String>() {{
            put("volume.beta.kubernetes.io/storage-class", "client-cephfs");
        }});
        meta.setName("mysql-client-cephfs-pv");
        //设置pv的metadata
        pv.setMetadata(meta);

        PersistentVolumeSpec pvs = new PersistentVolumeSpec();
        Map<String, Quantity> capacityMap = new HashMap<String, Quantity>();
        Quantity quantity = new Quantity();
        quantity.setAmount("2Gi");
        capacityMap.put("storage", quantity);
        //设置Spec的capacity
        pvs.setCapacity(capacityMap);

        List<String> accessModes = new ArrayList<String>();
        accessModes.add("ReadWriteMany");
        //设置Spec的accessModes
        pvs.setAccessModes(accessModes);
        //设置Spec的回收pvc的回收策略。
        pvs.setPersistentVolumeReclaimPolicy("Recycle");

        CephFSVolumeSource cephFSVolumeSource = new CephFSVolumeSource();
        //设置ceph的monitors
        cephFSVolumeSource.setMonitors(Arrays.asList("10.112.101.141:6789", "10.112.101.142:6789", "10.112.101.143:6789"));
        cephFSVolumeSource.setPath("/rbd12");
        //设置连接ceph的用户
        cephFSVolumeSource.setUser("admin");
        LocalObjectReference localObjectReference = new LocalObjectReference();
        localObjectReference.setName("ceph-secret");
        //        cephFSVolumeSource.setSecretFile("/etc/ceph/ceph.client.admin.keyring");
        cephFSVolumeSource.setSecretRef(localObjectReference);
        cephFSVolumeSource.setReadOnly(false);
        pvs.setCephfs(cephFSVolumeSource);

        //设置pv的Spec
        pv.setSpec(pvs);
        try {
            //将pv信息存储到服务端
            kubernetesClient.persistentVolumes().create(pv);
            System.out.println("创建挂载cephfs的pv成功");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 创建pvc信息
     *
     * @param kubernetesClient
     */
    public static void testCreatePvcFS(KubernetesClient kubernetesClient) {
        PersistentVolumeClaim pvc = new PersistentVolumeClaim();
        pvc.setApiVersion("v1");
        pvc.setKind("PersistentVolumeClaim");

        ObjectMeta meta = new ObjectMeta();
        meta.setName("mysql-client-cephfs-pvc");
        //设置pvc的metadata
        meta.setAnnotations(new HashMap<String, String>() {{
            put("volume.beta.kubernetes.io/storage-class", "client-cephfs");
        }});
        pvc.setMetadata(meta);

        PersistentVolumeClaimSpec pvcs = new PersistentVolumeClaimSpec();

        List<String> accessModes = new ArrayList<String>();
        accessModes.add("ReadWriteMany");
        //设置Spec的accessModes
        pvcs.setAccessModes(accessModes);
        //设置Spec绑定的pv
        pvcs.setVolumeName("mysql-client-cephfs-pv");

        ResourceRequirements resources = new ResourceRequirements();
        Map<String, Quantity> requests = new HashMap<String, Quantity>();
        Quantity quantity = new Quantity();
        quantity.setAmount("2Gi");
        requests.put("storage", quantity);
        resources.setRequests(requests);
        //设置Spec的Resources
        pvcs.setResources(resources);

        LabelSelector labelSelector = new LabelSelector();
        Map<String, String> matchLabels = new HashMap<String, String>();
        matchLabels.put("app", "mysql-client-cephfs-pvc-lbl");
        labelSelector.setMatchLabels(matchLabels);
        //设置Spec的Selector
        pvcs.setSelector(labelSelector);

        //设置pvc的Spec
        pvc.setSpec(pvcs);
        try {
            //将pvc信息存储到服务端
            kubernetesClient.persistentVolumeClaims().create(pvc);
            System.out.println("创建pvc成功");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 创建pv信息，挂载Rbd存储
     *
     * @param kubernetesClient
     */
    public static void testCreatePv_Rbd(KubernetesClient kubernetesClient) {
        PersistentVolume pv = new PersistentVolume();
        pv.setApiVersion("v1");
        pv.setKind("PersistentVolume");

        ObjectMeta meta = new ObjectMeta();
        meta.setName("mysql-client-pv");
        //设置pv的metadata
        pv.setMetadata(meta);

        PersistentVolumeSpec pvs = new PersistentVolumeSpec();
        Map<String, Quantity> capacityMap = new HashMap<String, Quantity>();
        Quantity quantity = new Quantity();
        quantity.setAmount("2Gi");
        capacityMap.put("storage", quantity);
        //设置Spec的capacity
        pvs.setCapacity(capacityMap);

        List<String> accessModes = new ArrayList<String>();
        accessModes.add("ReadWriteOnce");
        //设置Spec的accessModes
        pvs.setAccessModes(accessModes);
        //设置Spec的回收pvc的回收策略。
        pvs.setPersistentVolumeReclaimPolicy("Recycle");

        RBDVolumeSource rbdVolumeSource = new RBDVolumeSource();
        //设置ceph的monitors
        rbdVolumeSource.setMonitors(Arrays.asList("10.112.101.141:6789", "10.112.101.142:6789", "10.112.101.143:6789"));
        //设置ceph使用的存储池，ceph中默认是rbd
        rbdVolumeSource.setPool("rbd");
        //设置该pv要用的ceph的image
        rbdVolumeSource.setImage("hzb-mysql");
        //设置连接ceph的用户
        rbdVolumeSource.setUser("admin");
        //设置admin用户的认证信息
        rbdVolumeSource.setKeyring("C:\\Users\\yintongjiang\\.kube\\ceph.client.admin.keyring");
        //设置要以哪种格式来格式化image
        rbdVolumeSource.setFsType("xfs");
        //设置image的读写权限
        rbdVolumeSource.setReadOnly(false);
        pvs.setRbd(rbdVolumeSource);

        //设置pv的Spec
        pv.setSpec(pvs);
        try {
            //将pv信息存储到服务端
            kubernetesClient.persistentVolumes().create(pv);
            System.out.println("创建挂载rbd的pv成功");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 创建pvc信息
     *
     * @param kubernetesClient
     */
    public static void testCreatePvc(KubernetesClient kubernetesClient) {
        PersistentVolumeClaim pvc = new PersistentVolumeClaim();
        pvc.setApiVersion("v1");
        pvc.setKind("PersistentVolumeClaim");

        ObjectMeta meta = new ObjectMeta();
        meta.setName("mysql-client-pvc");
        //设置pvc的metadata
        pvc.setMetadata(meta);

        PersistentVolumeClaimSpec pvcs = new PersistentVolumeClaimSpec();

        List<String> accessModes = new ArrayList<String>();
        accessModes.add("ReadWriteOnce");
        //设置Spec的accessModes
        pvcs.setAccessModes(accessModes);
        //设置Spec绑定的pv
        pvcs.setVolumeName("mysql-client-pv");

        ResourceRequirements resources = new ResourceRequirements();
        Map<String, Quantity> requests = new HashMap<String, Quantity>();
        Quantity quantity = new Quantity();
        quantity.setAmount("2Gi");
        requests.put("storage", quantity);
        resources.setRequests(requests);
        //设置Spec的Resources
        pvcs.setResources(resources);

        LabelSelector labelSelector = new LabelSelector();
        Map<String, String> matchLabels = new HashMap<String, String>();
        matchLabels.put("app", "mysql-client-pvc-lbl");
        labelSelector.setMatchLabels(matchLabels);
        //设置Spec的Selector
        pvcs.setSelector(labelSelector);

        //设置pvc的Spec
        pvc.setSpec(pvcs);
        try {
            //将pvc信息存储到服务端
            kubernetesClient.persistentVolumeClaims().create(pvc);
            System.out.println("创建pvc成功");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
